package com.wedo.book.controller;

import com.wedo.book.bo.ChapterRequest;
import com.wedo.book.pojo.Chapter;
import com.wedo.book.service.ChapterService;
import com.wedo.common.pojo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("chapter")
public class ChapterController {

    @Autowired
    private ChapterService chapterService;

    /**
     * 分页查询章节基本信息
     * @param bid
     * @param page
     * @param rows
     * @return
     */
    @GetMapping("page")
    public ResponseEntity<PageResult<Chapter>> queryChapterByPage(
            @RequestParam("bid") Long bid,
            @RequestParam(value = "page",defaultValue = "1") Integer page,
            @RequestParam(value = "rows",defaultValue = "6") Integer rows
    ) {
        PageResult<Chapter> result = this.chapterService.queryChapterByPage(bid, page, rows);
        if (result == null||CollectionUtils.isEmpty(result.getItems())) {
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 根据章节id查询章节内容
     * @param cid
     * @return
     */
    @GetMapping("cid/{cid}")
    public ResponseEntity<Chapter> queryChapterById(@PathVariable("cid")Long cid) {
        Chapter result = this.chapterService.queryChapterById(cid);
        if (result == null) {
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 修改章节信息
     * @param chapterRequest
     * @return
     */
    @PostMapping
    public ResponseEntity<ChapterRequest> addChapter(@RequestBody ChapterRequest chapterRequest) {
        this.chapterService.saveChapter(chapterRequest);
        return ResponseEntity.ok(chapterRequest);
    }

    /**
     * 修改章节信息
     * @param chapter
     * @return
     */
    @PutMapping
    public ResponseEntity<Chapter> updateChapter(@RequestBody Chapter chapter) {
        this.chapterService.updateChapter(chapter);
        return ResponseEntity.ok(chapter);
    }

    @DeleteMapping
    public ResponseEntity<Chapter> deleteChapterById(@RequestBody Chapter chapter) {
        this.chapterService.deleteChapter(chapter.getId());
        return ResponseEntity.ok(chapter);
    }

    @GetMapping("lastOrNext")
    public ResponseEntity<Chapter> getLast(@RequestParam("cid")Long cid,@RequestParam(value = "type",defaultValue = "1")Integer type) {
        if (cid == null) {
            return ResponseEntity.badRequest().build();
        }
        Chapter chapter = this.chapterService.getLastOrNext(cid,type);
        return ResponseEntity.ok(chapter);
    }

}
